<?php
namespace app\user\controller;

use think\Controller;
use tp5_lib\user\model\UserModel;
use tp5_lib\user\model\MobileCodeModel;
use tp5_lib\aliyun\utility\Sms;

/**
 * 手机短信验证码接口
 * 网页和API共用
 */
class SmsController extends Controller
{
    //发送快速注册的验证码
    public function sendRegisterCode()
    {
        $mobile=input("mobile");
        if(!$mobile){
            $this->error("手机号不能为空");
        }
        $um=new UserModel;
        $user=$um->where(["mobile"=>$mobile])->find();
        if($user){
            $this->error("手机号已被占用");
        }
        $mcm=new MobileCodeModel;
        $result=$mcm->send($mobile,"register");
        if(!$result){
            $this->error($mcm->getError());
        }
        Sms::instance()->sendVerifyCode($mobile,$result["code"]);
        $this->success("发送成功,手机号:$mobile");
    }
    //发送手机登录的手机验证码
    public function sendLoginCode()
    {
        $mobile=input("mobile");
        if(!$mobile){
            $this->error("手机号不能为空");
        }
        $um=new UserModel;
        $user=$um->where(["mobile"=>$mobile])->find();
        if(!$user){
            $this->error("手机号未注册");
        }
        $mcm=new MobileCodeModel;
        $result=$mcm->send($mobile,"login");
        if(!$result){
            $this->error($mcm->getError());
        }
        Sms::instance()->sendVerifyCode($mobile,$result["code"]);
        $this->success("发送成功,手机号:$mobile");
    }
    //发送绑定手机号的手机验证码
    public function sendBindCode()
    {
        $mobile=input("mobile");
        if(!$mobile){
            $this->error("手机号不能为空");
        }
        $um=new UserModel;
        $user=$um->where(["mobile"=>$mobile])->find();
        if($user){
            $this->error("手机号已被占用");
        }
        $mcm=new MobileCodeModel;
        $result=$mcm->send($mobile,"bind_mobile");
        if(!$result){
            $this->error($mcm->getError());
        }
        Sms::instance()->sendVerifyCode($mobile,$result["code"]);
        $this->success("发送成功,手机号:$mobile");
    }
    //发送找回密码的手机验证码
    public function sendFindbackCode()
    {
        $username=input("username");
        if(!$username){
            $this->error("用户账号不能为空");
        }
        $um=new UserModel;
        $user=$um->findUser($username);
        // where(["username"=>$username])->find();
        if(!$user){
            $this->error("用户账号错误");
        }
        $mobile=$user["mobile"];
        $mcm=new MobileCodeModel;
        $result=$mcm->send($mobile,"findback");
        if(!$result){
            $this->error($mcm->getError());
        }
        Sms::instance()->sendVerifyCode($mobile,$result["code"]);
        $this->success("发送成功,手机号:$mobile");
    }
}
